package ru.dc.gui.swing;

import org.jdesktop.observablecollections.ObservableCollections;
import org.jdom.JDOMException;
import ru.dc.Application;
import ru.dc.object.ServerInfo;
import ru.dc.object.Settings;
import ru.swing.html.Bind;
import ru.swing.html.Binder;
import ru.swing.html.DomModel;
import ru.swing.html.ModelElement;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.util.*;
import java.util.List;

public class ConnectionParamsDlg extends JDialog {


    private int result = JOptionPane.CANCEL_OPTION;

    @ModelElement("encodings")
    private java.util.List<String> encodings = ObservableCollections.observableList(Arrays.asList("Windows-1251", "UTF-8"));

    @ModelElement("model")
    private ServerInfo model;


    public void onOK() {
        result = JOptionPane.OK_OPTION;
        dispose();
    }

    public void onCancel() {
        result = JOptionPane.CANCEL_OPTION;
        dispose();
    }


    public int execute() {

        model = new ServerInfo();

        final Settings settings = Application.getApplication().getSettings();
        model.setNick(settings.getNick());
        model.setEncoding(settings.getEncoding());
        model.setActive(settings.getMode() == Settings.MODE_ACTIVE);


        DomModel domModel;
        try {
            domModel = Binder.bind(this, true);
        } catch (JDOMException e) {
            e.printStackTrace();
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            return result;
        }



        setLocation((int) (Toolkit.getDefaultToolkit().getScreenSize().getWidth() -getWidth())/2,
                (int) (Toolkit.getDefaultToolkit().getScreenSize().getHeight() -getHeight())/3);
        getRootPane().setDefaultButton((JButton) domModel.query("#okBtn").get(0).getComponent());
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                onCancel();
            }
        });
        domModel.query("#rootPanel").get(0).getComponent().registerKeyboardAction(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);



        setVisible(true);
        return result;
    }

    public ServerInfo getServerInfo() {
        ServerInfo res = new ServerInfo();
        if (model.getAddress().indexOf(":")>0) {
            String[] tokens = model.getAddress().split(":");
            res.setAddress(tokens[0]);
            res.setPort(new Integer(tokens[1]));
        }
        else {
            res.setAddress(model.getAddress());
            res.setPort(411);
        }

        res.setEncoding(model.getEncoding());
        res.setNick(model.getNick());
        res.setActive(model.isActive());
        return res;
    }

}
